#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use 
# under the terms of the LICENSE.md file.
#
# For inquiries contact  george.drettakis@inria.fr
#

import os
from typing import List, Tuple, Dict, Callable, Any

import torch
from torch import nn
import torch.nn.functional as F
from torch.optim import Optimizer
from torch import Tensor
from torch.nn import Parameter
import numpy as np
from numpy import ndarray
from plyfile import PlyData, PlyElement
from simple_knn._C import distCUDA2

from hparam import HyperParams, OptimizationParams, low_freq_opt, high_freq_opt
from scene.embedding import Embedding
from utils.system_utils import mkdir_p
from utils.graphics_utils import BasicPointCloud
from utils.general_utils import strip_symmetric, build_scaling_rotation
from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation
from utils.sh_utils import RGB2SH

class GaussianModel(nn.Module):

    ''' mlp-gs '''

    def __init__(self, hp:HyperParams, opt:OptimizationParams):
        super(GaussianModel, self).__init__()

        # props
        self._xyz:      Parameter = None
        self._features: Parameter = None
        self._scaling:  Parameter = None
        self._rotation: Parameter = None
        self._opacity:  Parameter = None
        # optim1
        self.optimizer:        Optimizer = None
        self.xyz_scheduler:    Callable  = None
        self.xyz_grad_accum:   Tensor    = None
        self.xyz_grad_count:   Tensor    = None
        self.max_radii2D:      Tensor    = None
        
        self.spatial_lr_scale: float     = 1.0
        self.active_sh_degree            = 0  
        self.max_sh_degree               = opt.max_sh_degree 
        # consts
        self.hp = hp
        self.opt = opt
        self.percent_dense = opt.percent_dense                      #小于或等于percent_dense的点进行clone，大于percent_dense的点split，freq0应该增加，减少被认为是密集的比例
        self.densify_grad_threshold = opt.densify_grad_threshold    #稠密梯度阈值，梯度值高于此阈值则进行split或clone
        self.min_opacity = opt.min_opacity                          #不透明度阈值，低于此阈值应被剪除
        self.max_screen_size = opt.max_screen_size                  #点在屏幕上显示的最大尺寸，剪枝过大的点
        self.sample_ratio = opt.sample_ratio                        #间隔几个采样
        self.init_scaling = opt.init_scaling                        #初始点云大小
        self.color_scale = opt.color_scale
        self.extent_scale = opt.extent_scale
        self.precomp_color_from_SHs = opt.precomp_color_from_SHs
        
        self.setup_transform_functions()        

    def setup_transform_functions(self):
        def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):
            L = build_scaling_rotation(scaling_modifier * scaling, rotation)
            actual_covariance = L @ L.transpose(1, 2)
            symm = strip_symmetric(actual_covariance)
            return symm

        self.scaling_activation = torch.exp
        self.scaling_inverse_activation = torch.log
        self.rotation_activation = F.normalize
        self.opacity_activation = torch.sigmoid
        self.opacity_inverse_activation = inverse_sigmoid
        self.covariance_activation = build_covariance_from_scaling_rotation       

    @property
    def n_points(self):
        return self.get_xyz.shape[0]
    
    @property
    def get_scaling(self):
        return self.scaling_activation(self._scaling)
    
    @property
    def get_rotation(self):
        return self.rotation_activation(self._rotation)
    
    @property
    def get_xyz(self):
        return self._xyz
    
    @property
    def get_features(self):
        features_dc = self._features_dc
        features_rest = self._features_rest
        return torch.cat((features_dc, features_rest), dim=1)
    
    def oneupSHdegree(self):
        if self.active_sh_degree < self.max_sh_degree:
            self.active_sh_degree += 1
    
    @property
    def get_opacity(self):
        return self.opacity_activation(self._opacity)
        
    def get_covariance(self, scaling_modifier=1):
        return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)

    def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):
        self.spatial_lr_scale = spatial_lr_scale
        
        fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()[::self.sample_ratio]
        fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())
        features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()
        features[:, :3, 0 ] = fused_color 
        features[:, 3:, 1:] = 0.0  

        # distCUDA2 计算点云中的每个点到与其最近的 K 个点的平均距离的平方：(N, )
        dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
        scales = self.init_scaling * torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)        # (N, 3)
        rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")  # (N, 4)
        rots[:, 0] = 1

        opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))

        self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))    # (N, 3)
        self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))   # (N, 1, 3)
        self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))  # (N, 15, 3)
        self._scaling = nn.Parameter(scales.requires_grad_(True))           # (N, 3)
        self._rotation = nn.Parameter(rots.requires_grad_(True))            # (N, 4)
        self._opacity = nn.Parameter(opacities.requires_grad_(True))        # (N, 1)
        self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")   # (N, )

    def training_setup(self):
        training_args = self.opt
        self.xyz_grad_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")    # (N, 1)
        self.xyz_grad_count = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")    # (N, 1)

        l = [
            {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
            {'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
            {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
            {'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
            {'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
            {'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
        ]
        
        self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
        self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
                                                    lr_final=training_args.position_lr_final*self.spatial_lr_scale,
                                                    lr_delay_mult=training_args.position_lr_delay_mult,
                                                    max_steps=training_args.position_lr_max_steps)
                        
    def update_learning_rate(self, iteration):
        ''' Learning rate scheduling per step '''
        for param_group in self.optimizer.param_groups:
            if param_group["name"] == "xyz":
                lr = self.xyz_scheduler_args(iteration)
                param_group['lr'] = lr

    def reset_opacity(self):
        opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))
        optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity")
        self._opacity = optimizable_tensors["opacity"]

    def replace_tensor_to_optimizer(self, tensor, name):
        optimizable_tensors = {}
        for group in self.optimizer.param_groups:
            if group["name"] == name:
                stored_state = self.optimizer.state.get(group['params'][0], None)
                stored_state["exp_avg"] = torch.zeros_like(tensor)
                stored_state["exp_avg_sq"] = torch.zeros_like(tensor)

                del self.optimizer.state[group['params'][0]]
                group["params"][0] = nn.Parameter(tensor.requires_grad_(True))
                self.optimizer.state[group['params'][0]] = stored_state

                optimizable_tensors[group["name"]] = group["params"][0]
        return optimizable_tensors

    def _prune_optimizer(self, mask):
        optimizable_tensors = {}
        for group in self.optimizer.param_groups:
            stored_state = self.optimizer.state.get(group['params'][0], None)
            if stored_state is not None:
                stored_state["exp_avg"] = stored_state["exp_avg"][mask]
                stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask]

                del self.optimizer.state[group['params'][0]]
                group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True)))
                self.optimizer.state[group['params'][0]] = stored_state

                optimizable_tensors[group["name"]] = group["params"][0]
            else:
                group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True))
                optimizable_tensors[group["name"]] = group["params"][0]
        return optimizable_tensors

    def prune_points(self, mask):
        valid_points_mask = ~mask
        optimizable_tensors = self._prune_optimizer(valid_points_mask)

        self._xyz = optimizable_tensors["xyz"]
        self._features_dc = optimizable_tensors["f_dc"]
        self._features_rest = optimizable_tensors["f_rest"]
        self._opacity = optimizable_tensors["opacity"]
        self._scaling = optimizable_tensors["scaling"]
        self._rotation = optimizable_tensors["rotation"]

        self.xyz_grad_accum = self.xyz_grad_accum[valid_points_mask]
        self.xyz_grad_count = self.xyz_grad_count[valid_points_mask]
        self.max_radii2D = self.max_radii2D[valid_points_mask]

    def cat_tensors_to_optimizer(self, tensors_dict):
        optimizable_tensors = {}
        for group in self.optimizer.param_groups:
            if group['name'] in ['color_mlp', 'embedding_appearance']:
                continue
            assert len(group["params"]) == 1
            extension_tensor = tensors_dict[group["name"]]
            stored_state = self.optimizer.state.get(group['params'][0], None)
            if stored_state is not None:

                stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0)
                stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0)

                del self.optimizer.state[group['params'][0]]
                group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
                self.optimizer.state[group['params'][0]] = stored_state

                optimizable_tensors[group["name"]] = group["params"][0]
            else:
                group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
                optimizable_tensors[group["name"]] = group["params"][0]

        return optimizable_tensors

    def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):
        d = {"xyz": new_xyz,
            "f_dc": new_features_dc,
            "f_rest": new_features_rest,
            "opacity": new_opacities,
            "scaling" : new_scaling,
            "rotation" : new_rotation}

        optimizable_tensors = self.cat_tensors_to_optimizer(d)
        self._xyz = optimizable_tensors["xyz"]              # (N+P, 3)
        self._features_dc = optimizable_tensors["f_dc"]     # (N+P, 1)
        self._features_rest = optimizable_tensors["f_rest"] # (N+P, 15)
        self._opacity = optimizable_tensors["opacity"]      # (N+P, 1)
        self._scaling = optimizable_tensors["scaling"]      # (N+P, 3)
        self._rotation = optimizable_tensors["rotation"]    # (N+P, 4)

        self.xyz_grad_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
        self.xyz_grad_count = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
        self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
 
    def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):
        n_init_points = self.get_xyz.shape[0]
        padded_grad = torch.zeros((n_init_points), device="cuda")
        padded_grad[:grads.shape[0]] = grads.squeeze()
        
        selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)
        selected_pts_mask = torch.logical_and(selected_pts_mask,
                                              torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)
        
        # print(f"grad_threshold: {self.densify_grad_threshold}, densify extend: {self.percent_dense*scene_extent}, split num {selected_pts_mask.sum()}")
        stds = self.get_scaling[selected_pts_mask].repeat(N,1)  # (P, 3)
        means = torch.zeros((stds.size(0), 3),device="cuda")    # (P, 3)
        samples = torch.normal(mean=means, std=stds)            # (P, 3)
        rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1)
        new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask].repeat(N, 1)
        new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))
        new_rotation = self._rotation[selected_pts_mask].repeat(N,1)
        new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)
        new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)
        new_opacity = self._opacity[selected_pts_mask].repeat(N,1)

        self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)
        prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device="cuda", dtype=bool)))
        self.prune_points(prune_filter)

    def densify_and_clone(self, grads, grad_threshold, scene_extent):
        selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)
        selected_pts_mask = torch.logical_and(selected_pts_mask,
                                              torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)
        
        # print(f"grad_threshold: {self.densify_grad_threshold}, densify extend: {self.percent_dense*scene_extent}, clone num {selected_pts_mask.sum()}")
        new_xyz = self._xyz[selected_pts_mask]                      # (P, 3)
        new_features_dc = self._features_dc[selected_pts_mask]      # (P, 1)
        new_features_rest = self._features_rest[selected_pts_mask]  # (P, 15)
        new_opacities = self._opacity[selected_pts_mask]            # (P, 1)
        new_scaling = self._scaling[selected_pts_mask]              # (P, 3)
        new_rotation = self._rotation[selected_pts_mask]            # (P, 4)

        self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)

    def densify_and_prune(self, extent, iters):
        max_grad = self.densify_grad_threshold
        min_opacity = self.min_opacity
        extent_scale = self.extent_scale
        max_screen_size = self.max_screen_size if iters > self.hp.opacity_reset_interval else None
        
        xyz_grads = self.xyz_grad_accum / self.xyz_grad_count
        xyz_grads[xyz_grads.isnan()] = 0.0
                
        self.densify_and_clone(xyz_grads, max_grad, extent)
        self.densify_and_split(xyz_grads, max_grad, extent)

        prune_mask = (self.get_opacity < min_opacity).squeeze()
        # print(f"min_opacity: {min_opacity}, prune num: {prune_mask.sum()}")
        
        if max_screen_size:
            big_points_vs = self.max_radii2D > max_screen_size
            # print(f"max_screen_size: {max_screen_size}, 2D prune num: {big_points_vs.sum()}")
            big_points_ws = self.get_scaling.max(dim=1).values > extent_scale * extent
            # print(f"extent: {extent}, 3D prune num: {big_points_ws.sum()}")
            prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)
        
        self.prune_points(prune_mask)
        torch.cuda.empty_cache()

    def add_densification_stats(self, viewspace_point_tensor, update_filter):
        self.xyz_grad_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)
        self.xyz_grad_count[update_filter] += 1

    def construct_list_of_attributes(self):
        l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
        # All channels except the 3 DC
        for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
            l.append('f_dc_{}'.format(i))
        for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
            l.append('f_rest_{}'.format(i))
        l.append('opacity')
        for i in range(self._scaling.shape[1]):
            l.append('scale_{}'.format(i))
        for i in range(self._rotation.shape[1]):
            l.append('rot_{}'.format(i))
        return l

    def save_ply(self, path):
        mkdir_p(os.path.dirname(path))

        xyz = self._xyz.detach().cpu().numpy()  # (N, 3)
        normals = np.zeros_like(xyz)            # (N, 3)
        f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()       # (N, 3)
        f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()   # (N, 15*3)
        opacities = self._opacity.detach().cpu().numpy()    # (N, 1)
        scale = self._scaling.detach().cpu().numpy()        # (N, 3)
        rotation = self._rotation.detach().cpu().numpy()    # (N, 4)

        dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]

        elements = np.empty(xyz.shape[0], dtype=dtype_full)
        attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
        elements[:] = list(map(tuple, attributes))
        el = PlyElement.describe(elements, 'vertex')
        PlyData([el]).write(path)
        
    def load_ply(self, path):
        plydata = PlyData.read(path)

        xyz = np.stack((np.asarray(plydata.elements[0]["x"]),
                        np.asarray(plydata.elements[0]["y"]),
                        np.asarray(plydata.elements[0]["z"])),  axis=1)
        opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis]

        features_dc = np.zeros((xyz.shape[0], 3, 1))
        features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"])
        features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"])
        features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"])

        extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")]
        extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))
        assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3
        features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))
        for idx, attr_name in enumerate(extra_f_names):
            features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])
        # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)
        features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))

        scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")]
        scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))
        scales = np.zeros((xyz.shape[0], len(scale_names)))
        for idx, attr_name in enumerate(scale_names):
            scales[:, idx] = np.asarray(plydata.elements[0][attr_name])

        rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")]
        rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))
        rots = np.zeros((xyz.shape[0], len(rot_names)))
        for idx, attr_name in enumerate(rot_names):
            rots[:, idx] = np.asarray(plydata.elements[0][attr_name])

        self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True))
        self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
        self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
        self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True))
        self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True))
        self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True))

        self.active_sh_degree = self.max_sh_degree

    def state_dict(self) -> Dict[str, Any]:
        state_dict = {
            # props
            '_xyz':             self._xyz,
            '_scaling':         self._scaling,
            '_rotation':        self._rotation,
            '_opacity':         self._opacity,
            '_features_dc':     self._features_dc,
            '_features_rest':   self._features_rest,
            # optim
            'optimizer':        self.optimizer.state_dict(),
            'xyz_grad_accum':   self.xyz_grad_accum,
            'xyz_grad_count':   self.xyz_grad_count,
            'max_radii2D':      self.max_radii2D,
            'percent_dense':    self.percent_dense,
            'spatial_lr_scale': self.spatial_lr_scale,
        }
        return state_dict
    
    def load_state_dict(self, state_dict:Dict[str, Any]):
        # load data first
        self._xyz      = state_dict['_xyz']
        self._scaling  = state_dict['_scaling']
        self._rotation = state_dict['_rotation']
        self._opacity  = state_dict['_opacity']
        self._features = state_dict['_features']
        self._opacity  = state_dict['_opacity']
        self.color_mlp.load_state_dict(state_dict['color_mlp'])
        # then recover optim state
        self.optimizer.load_state_dict(state_dict['optimizer'])
        self.xyz_grad_accum   = state_dict['xyz_grad_accum']
        self.xyz_grad_count   = state_dict['xyz_grad_count']
        self.max_radii2D      = state_dict['max_radii2D']
        self.percent_dense    = state_dict['percent_dense']
        self.spatial_lr_scale = state_dict['spatial_lr_scale']
        

class MutilFreqGaussianModel:

    def __init__(self, hp:HyperParams):
        self.hp = hp
        self.opts = [low_freq_opt, high_freq_opt]
        self.gaussians = {idx: GaussianModel(hp, self.opts[idx]) for idx in range(hp.n_freqs)}
        self.cur_idx = 0

        self.spatial_lr_scale = 1.0

    @property
    def n_gaussians(self):
        return len(self.gaussians)

    @property
    def cur_gaussian(self):
        return self.gaussians[self.cur_idx]

    def get_gaussian(self, idx:int):
        return self.gaussians[idx]

    def activate_gaussian(self, idx:int=0):
        last_idx = self.cur_idx
        if idx == last_idx: return
        self.cur_idx = idx

    def from_pcd(self, pcd:BasicPointCloud):
        for idx in range(self.hp.n_freqs):
            gaussians = self.get_gaussian(idx)
            gaussians.create_from_pcd(pcd, self.spatial_lr_scale)
            print(f'Number of points of freq_{idx} at initialization:', gaussians.n_points)
